/*
*********************************************************************************************************
*                                               uC/OS-II
*                                         The Real-Time Kernel
*
*                         (c) Copyright 2002, Jean J. Labrosse, Weston, FL
*                                          All Rights Reserved                         
*                                        MC9S12DP256 Specific code
*                                         MC9S12 Small Memory Model
*                               (CodeWarrior Development Studio V5.9.0)                                           
*
* File         : OS_CPU_C.C
* By           : LI Yuan
* Port Version : V2.52 and higher
*********************************************************************************************************
*/
#include <hidef.h>           /* common defines and macros */
#include "derivative.h"      /* derivative-specific definitions */
#include  "INCLUDES.H"
 
 
#if OS_CPU_HOOKS_EN > 0 && OS_VERSION > 203
 
void  OSInitHookBegin (void)
{
    #if OS_TMR_EN > 0
        OSTmrCtr = 0;
    #endif
}
 
void  OSInitHookEnd (void)
{
}
 
#endif
 
 
#if OS_CPU_HOOKS_EN > 0
 
void  OSTaskCreateHook (OS_TCB *ptcb)
{
    #if OS_APP_HOOKS_EN > 0
        App_TaskCreateHook(ptcb);
    #else
        (void)ptcb; 
    #endif
}
 
void  OSTaskDelHook (OS_TCB *ptcb)
{
    #if OS_APP_HOOKS_EN > 0
        App_TaskDelHook(ptcb);
    #else
        (void)ptcb;  
    #endif
}
 
 
void  OSTaskStatHook (void)
{
    #if OS_APP_HOOKS_EN > 0
        App_TaskStatHook();
    #endif
}
 
void  OSTaskSwHook (void)
{
    #if OS_APP_HOOKS_EN > 0
        App_TaskSwHook();
    #endif
}
 
#endif
 
 
#if OS_CPU_HOOKS_EN > 0 && OS_VERSION >= 251
void  OSTaskIdleHook (void)
{
    #if OS_APP_HOOKS_EN > 0
        App_TaskIdleHook();
    #endif
}
#endif
 
/*
*********************************************************************************************************
*                                        INITIALIZE A TASK'S STACK
*
* Description: This function is called by either OSTaskCreate() or OSTaskCreateExt() to initialize the
*              stack frame of the task being created.  This function is highly processor specific.
*
* Arguments  : task          is a pointer to the task code
*
*              pdata         is a pointer to a user supplied data area that will be passed to the task
*                            when the task first executes.
*
*              ptos          is a pointer to the top of stack.  It is assumed that 'ptos' points to
*                            a 'free' entry on the task stack.  If OS_STK_GROWTH is set to 1 then
*                            'ptos' will contain the HIGHEST valid address of the stack.  Similarly, if
*                            OS_STK_GROWTH is set to 0, the 'ptos' will contains the LOWEST valid address
*                            of the stack.
*
*              opt           specifies options that can be used to alter the behavior of OSTaskStkInit().
*                            (see uCOS_II.H for OS_TASK_OPT_???).
*
* Returns    : Always returns the location of the new top-of-stack' once the processor registers have
*              been placed on the stack in the proper order.
*
* Note(s)    : 1) XIRQ interrupts are disabled when your task starts executing. You can change this by
*                 clearing BIT6 in the CCR.
*              2) The STOP instruction is disabled when your task starts executing.  You can change this
*                 by clearing BIT7 in the CCR.
*              3) The other interrupts (i.e. maskable interrupts) are enabled when your task starts
*                 executing.  You can change this by setting BIT4 in the CCR.
*              4) You can change pass the above options in the 'opt' argument.  You MUST only use the
*                 upper 8 bits of 'opt' because the lower bits are reserved by uC/OS-II.  If you make
*                 changes to the code below, you will need to ensure that it doesn't affect the behaviour
*                 of OSTaskIdle() and OSTaskStat().
*              5) Registers are initialized to make them easy to differentiate with a debugger.
*              6) All your tasks are assumed to be in NON-PAGED memory.  However, the tasks can call
*                 functions in PAGED memory and if a context switch occurs, the proper page will be
*                 saved/restored by uC/OS-II.  Page #0 is stored onto the task's stack as a 'dummy'
*                 value.
*********************************************************************************************************
*/
 
OS_STK *OSTaskStkInit (void (*task)(void *pd), void *p_arg, OS_STK *ptos, INT16U opt)
{
    INT16U *wstk;
    INT8U  *bstk;
  
    (void) opt;                            /* 'opt' is not used, prevent warning                     */
    ptos--;                                /* 需要这么调整一下栈顶地址，否则存的第一个int16 的低 Byte 会溢出堆栈 */
    wstk  = (INT16U *)ptos;                /* Load stack pointer                                     */
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)   
    *wstk-- = (INT32U)task >> 8;             /* Return address.  Format: PCH:PCL:PPAGE                 */
#else
    *wstk-- = (INT16U)task;
#endif
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)   
    *wstk-- = (INT32U)task >> 8;             /* Return address.  Format: PCH:PCL:PPAGE                 */
#else
    *wstk-- = (INT16U)task;
#endif   
 
    *wstk-- = (INT16U)0x2222;                /* Y Register                                             */
    *wstk-- = (INT16U)0x1111;                /* X Register                                             */
    *wstk   = (INT16U)p_arg;                 /* Simulate call to function with argument (In D Register) */ 
     bstk    = (INT8U *)wstk;                /* Convert WORD ptr to BYTE ptr to set CCR                */
     bstk--;
    *bstk = (0xC0);                        /* CCR Register (Disable STOP instruction and XIRQ)       */
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    *--bstk = (INT8U)task;                 /* Save the PPAGE register                                */
#endif   
 
    return ((OS_STK *)bstk);               /* Return pointer to new top-of-stack                     */  
}
 
 
/*
*********************************************************************************************************
*                                           OSTCBInit() HOOK
*
* Description: This function is called by OS_TCBInit() after setting up most of the TCB.
*
* Arguments  : ptcb    is a pointer to the TCB of the task being created.
*
* Note(s)    : 1) Interrupts may or may not be ENABLED during this call.
*********************************************************************************************************
*/
#if OS_CPU_HOOKS_EN > 0 && OS_VERSION > 203
void  OSTCBInitHook (OS_TCB *ptcb)
{
#if OS_APP_HOOKS_EN > 0
    App_TCBInitHook(ptcb);
#else
    (void)ptcb;                                                         /* Prevent compiler warning                                 */
#endif
}
#endif
 
 
/*
*********************************************************************************************************
*                                               TICK HOOK
*
* Description: This function is called every tick.
*
* Arguments  : none
*
* Note(s)    : 1) Interrupts may or may not be ENABLED during this call.
*********************************************************************************************************
*/
#if OS_CPU_HOOKS_EN > 0
void  OSTimeTickHook (void)
{
#if OS_APP_HOOKS_EN > 0
    App_TimeTickHook();
#endif
 
#if OS_TMR_EN > 0
    OSTmrCtr++;
    if (OSTmrCtr >= (OS_TICKS_PER_SEC / OS_TMR_CFG_TICKS_PER_SEC))
    {
        OSTmrCtr = 0;
        OSTmrSignal();
    }
#endif
}
#endif
 
 
/*********************************************************************************************************
;                               START HIGHEST PRIORITY TASK READY-TO-RUN
;
; Description : This function is called by OSStart() to start the highest priority task that was created
;               by your application before calling OSStart().
;
; Arguments   : none
;
; Note(s)     : 1) The stack frame is assumed to look as follows:
;  
;                  OSTCBHighRdy->OSTCBStkPtr +  0  -->  PPAGE
;                                            +  1       CCR
;                                            +  2       B
;                                            +  3       A
;                                            +  4       X (H)
;                                            +  5       X (L)
;                                            +  6       Y (H)
;                                            +  7       Y (L)
;                                            +  8       PC(H)
;                                            +  9       PC(L)
;
;               2) OSStartHighRdy() MUST:
;                      a) Call OSTaskSwHook() then,
;                      b) Set OSRunning to TRUE,
;                      c) Switch to the highest priority task by loading the stack pointer of the
;                         highest priority task into the SP register and execute an RTI instruction.
;********************************************************************************************************/
 
#pragma CODE_SEG NON_BANKED
 
#pragma TRAP_PROC          
void OSStartHighRdy(void)
{
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)   
    __asm call OSTaskSwHook;   // OSTaskSwHook(); 
#else
    __asm jsr OSTaskSwHook;   // OSTaskSwHook();
#endif
     
    __asm ldab #$01;
    __asm stab OSRunning;     // OSRunning = TRUE;        
     
    __asm
    {
        ldx    OSTCBHighRdy    
        lds    0, x            
        nop                         
    }
     
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm pula;              //  3~, Get value of PPAGE register
    __asm staa   PPAGE;      //  3~, Store into CPU's PPAGE register
#endif
 
    //__asm rti;
}
 
/********************************************************************************************************
;                                       TASK LEVEL CONTEXT SWITCH
;
; Description : This function is called when a task makes a higher priority task ready-to-run.
;
; Arguments   : none
;
; Note(s)     : 1) Upon entry,
;                  OSTCBCur     points to the OS_TCB of the task to suspend
;                  OSTCBHighRdy points to the OS_TCB of the task to resume
;
;               2) The stack frame of the task to suspend looks as follows:
;
;                  SP +  0  -->  PPAGE
;                     +  1       CCR
;                     +  2       B
;                     +  3       A
;                     +  4       X (H)
;                     +  5       X (L)
;                     +  6       Y (H)
;                     +  7       Y (L)
;                     +  8       PC(H)
;                     +  9       PC(L)
;
;               3) The stack frame of the task to resume looks as follows:
;
;                  OSTCBHighRdy->OSTCBStkPtr +  0  -->  PPAGE
;                                            +  1       CCR
;                                            +  2       B
;                                            +  3       A
;                                            +  4       X (H)
;                                            +  5       X (L)
;                                            +  6       Y (H)
;                                            +  7       Y (L)
;                                            +  8       PC(H)
;                                            +  9       PC(L)
;*********************************************************************************************************/
 
 
interrupt VectorNumber_Vswi void OSCtxSw(void)
{
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm ldaa   PPAGE;           //  3~, Get current value of PPAGE register                               
    __asm psha;                   //  2~, Push PPAGE register onto current task's stack
#endif
 
    __asm
    {
        ldx OSTCBCur              ;  3~, OSTCBCur->OSTCBStkPtr = Stack Pointer                     
        sts 0, x                  ;  3~      
    }                
                               
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm call OSTaskSwHook;      // 4~, Call user task switch hook
#else
 
    __asm jsr OSTaskSwHook;      // 4~, Call user task switch hook                      
#endif
     
    __asm
    {   
      ldx OSTCBHighRdy            ;  3~, OSTCBCur  = OSTCBHighRdy
      stx OSTCBCur                ;  3~                        
    }
     
    __asm
    {
      ldab OSPrioHighRdy          ;  3~, OSPrioCur = OSPrioHighRdy                       
      stab OSPrioCur              ;  3~
    }
     
    __asm lds 0, x;               // 3~, Load SP into 68HC12                             
     
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm pula;                   // 3~, Get value of PPAGE register
    __asm staa PPAGE;             // 3~, Store into CPU's PPAGE register                               
#endif
 
    __asm nop;   
    //__asm rti;                    // 8~, Run task
} 
 
  
/********************************************************************************************************
;                                    INTERRUPT LEVEL CONTEXT SWITCH
;
; Description : This function is called by OSIntExit() to perform a context switch to a task that has
;               been made ready-to-run by an ISR.
;
; Arguments   : none
;********************************************************************************************************/
interrupt void OSIntCtxSw(void)
{
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm call OSTaskSwHook;      // 4~, Call user task switch hook                      
#else
    __asm jsr OSTaskSwHook;      // 4~, Call user task switch hook                      
#endif
     
    __asm
    {   
      ldx OSTCBHighRdy            ;  3~, OSTCBCur  = OSTCBHighRdy
      stx OSTCBCur                ;  3~                        
    }
     
    __asm
    {
      ldab OSPrioHighRdy          ;  3~, OSPrioCur = OSPrioHighRdy                       
      stab OSPrioCur              ;  3~
    }
     
    __asm lds 0, x;               // 3~, Load SP into 68HC12                             
     
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm pula;                   // 3~, Get value of PPAGE register
    __asm staa PPAGE;             // 3~, Store into CPU's PPAGE register                               
#endif
 
    __asm nop;   
    //__asm rti;                    // 8~, Run task
}
 
  
/*********************************************************************************************************
 
;                                           SYSTEM TICK ISR
;
; Description : This function is the ISR used to notify uC/OS-II that a system tick has occurred.  You
;               must setup the 68HC12's interrupt vector table so that an OUTPUT COMPARE interrupt
;               vectors to this function.
;
; Arguments   : none
;
; Notes       :  1) The 'tick ISR' assumes the we are using the Output Compare specified by OS_TICK_OC
;                   (see OS_CFG.H and this file) to generate a tick that occurs every OS_TICK_OC_CNTS
;                   (see OS_CFG.H and this file) which corresponds to the number of FRT (Free Running
;                   Timer) counts to the next interrupt.
;
;
;                3) TFLG1, TC0 ... TC7 are defined in 6812dp256.h.
;********************************************************************************************************/
interrupt VectorNumber_Vrti void OSTickISR (void)
{
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm ldaa   PPAGE;           //  3~, Get current value of PPAGE register                               
    __asm psha;                   //  2~, Push PPAGE register onto current task's stack
#endif
      
    __asm inc OSIntNesting;      //OSIntNesting++;
 
    //if (OSIntNesting == 1)
    //{
    //    OSTCBCur->OSTCBStkPtr = Stack Pointer ;
    //}
    __asm
    {
      ldab OSIntNesting          
      cmpb #$01                 
      bne OSTickISR1       
 
      ldx OSTCBCur          
      sts 0, x  
OSTickISR1:                                                    
    }
 
    
    //CRGFLG_RTIF = 1;              // clear interrupt flag.
    __asm BSET _CRGFLG, #128;
 
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm call OSTimeTick;          //OSTimeTick();
    __asm call OSIntExit;           //OSIntExit ();
#else
    __asm jsr OSTimeTick;          //OSTimeTick();
    __asm jsr OSIntExit;           //OSIntExit ();
#endif
 
 
     
#if defined( __BANKED__) || defined(__LARGE__) || defined(__PPAGE__)
    __asm pula;                   // 3~, Get value of PPAGE register
    __asm staa PPAGE;             // 3~, Store into CPU's PPAGE register                               
#endif   
 
} 
 
 
#pragma CODE_SEG NONBANKED
 
#pragma NO_ENTRY
OS_CPU_SR OSCPUSaveSR( void )
{
__asm
    {
    tfr ccr, b                     // copy the value of CCR to the register B
    sei                            // Disable interrupts
    }
}
 
#pragma NO_ENTRY
void OSCPURestoreSR(OS_CPU_SR os_cpu_sr)
{
__asm
    {
      tfr  b, ccr
    }
} 

